<!--
 * @Description: 巡查任务管理页面
-->

<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="searchData"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>

    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>

    <template v-slot:table>
      <el-table ref="tableData" v-loading="loading" :data="tableData" stripe border height="calc(100% - 50px)"
        @row-click="handleEdit" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="inspectionTaskName" label="巡查任务名称" min-width="180" />
        <el-table-column prop="inspectionRouteName" label="巡查路线" />
        <el-table-column prop="employeeName" label="巡查人" />
        <el-table-column prop="generateTime" :formatter="dateFormat" label="巡查时间" />
        <el-table-column min-width="90" label="操作">
          <template v-if="btnFlag_delete || btnFlag_edit" slot-scope="scope">
            <el-button v-show="btnFlag_edit" class="text-btn-cursor" type="primary" plain @click="edit">
              修 改
            </el-button>
            <el-button v-show="btnFlag_delete" class="text-btn-cursor cursor-delete" type="danger" plain
              @click="handleDelete(scope.row)">
              删 除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize"  @current-change="changeCurrentPage" :page="currentPage" :total="totalSize">
      </Pagination>
    </template>

    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false"  :title="dialogTitle + '巡查任务信息'" :visible.sync="dialogFormVisible" :before-close="cancel">
        <el-form ref="formData" :model="formData" :rules="rules" class="el-form" label-width="120px">
          <el-form-item label="巡查任务名称:" prop="inspectionTaskName">
            <el-input v-model="formData.inspectionTaskName" placeholder="请输入巡查任务名称" clearable />
          </el-form-item>
          <el-form-item label="巡查线路选择:" prop="inspectionRouteId">
            <el-select class="w100p" v-model="formData.inspectionRouteId" clearable filterable @change="inspection">
              <el-option v-for="item in patrolLine" :key="item.inspectionRouteId" :label="item.inspectionRouteName"
                :value="item.inspectionRouteId" />
            </el-select>
          </el-form-item>
          <el-form-item label="巡查人:" prop="employeeName">
            <el-select class="w100p" v-model="formData.employeeName" clearable filterable @change="employee">
              <el-option v-for="(item, index) in person" :key="index" :label="item.person.name"
                :value="item.person.personNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="任务执行时间" prop="generateTime">
            <el-date-picker class="w100p" v-model="formData.generateTime" type="datetime" placeholder="请输入任务生成时间"
              clearable value-format="timestamp" />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import BtnSlot from '@/components/BtnSlot';

import InspectionTask from "@/api/patrol-info-manage/patrol-task-manage";
import patrolInfoManage from "@/api/patrol-info-manage/patrol-line-manage";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from 'vuex'
export default {
  name: "PatrolTaskManage",
  components: {
    MainSlot,
    Pagination,
    BtnSlot,
    SearchForm
  },
  mixins: [mymixin],
  data() {
    return {
      btnList: ['add', 'delete'],
      unfoldFlag: false,
      formItemList: [
        {
          label: '巡查任务名称',
          type: 'input',
          param: 'inspectionTaskName',
          defaultSelect: '',
          isShow: true
        },
        {
          label: '巡查路线',
          type: 'select',
          selectOptions: [],
          param: 'inspectionRouteId',
          defaultSelect: '',
          multiple: false,
          isShow: true
        },
        {
          label: '巡查人',
          type: 'select',
          selectOptions: [],
          param: 'employeeName',
          defaultSelect: '',
          multiple: false,
          isShow: true
        },
        {
          label: '巡查时间',
          type: 'daterange',
          param: 'dateList',
          defaultSelect: '',
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          isShow: true
        }
      ],
      searchFormData: {},
      searchlist: {},
      inspectionTaskName: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedStaffList: [],
      staffData: [],
      patrolLine: [],
      inspectionRouteId: "",
      employeeName: "",
      rules: {
        inspectionTaskName: [
          { required: true, message: "请输入巡查计划名称", trigger: "blur" }
        ],
        inspectionRouteId: [
          { required: true, message: "请选择巡查线路", trigger: "change" }
        ],
        employeeName: [
          { required: true, message: "请选择巡查人", trigger: "change" }
        ],
        generateTime: [
          { required: true, message: "请选择时间", trigger: "change" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false,
    };
  },
  computed: {
    ...mapGetters([
      'codeList'
    ]),
    person() {
      return this.$store.state.initData.person || [];
    },
    btnFlag_edit(){
      return this.codeList.indexOf('edit') !== -1;
    },
    btnFlag_delete(){
      return this.codeList.indexOf('delete') !== -1;
    }
  },
  created() {
    this.$nextTick(() => {
      this.search();
    });
  },
  mounted() {
    //  表格数据
    this.initData();
  },
  methods: {
    async initData() {
      let { data: patrolLine } = await patrolInfoManage.inspectionRouteCondition()
      this.patrolLine = patrolLine;
      this.setFormOptions();
    },

    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('inspectionRouteId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.patrolLine.map(data => {
            return {
              text: data.inspectionRouteName, value: data.inspectionRouteId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('employeeName') !== -1) {
          let selectOptions = this.person.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
        console.log(this.person)
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },

    searchData(data) {
      console.log(data)
      this.searchFormData = { ...data, dataTimeStart: '', dataTimeEnd: '' };
      if (data.dateList && data.dateList.length > 0) {
        this.searchFormData.dataTimeStart = `${data.dateList[0]} 00:00:00`
        this.searchFormData.dataTimeEnd = `${data.dateList[1]} 12:59:59`
      }
      console.log(this.searchFormData)
      this.getTableDataList();
    },
    getTableDataList() {
      this.tableData = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          inspectionTaskName: this.searchFormData.inspectionTaskName || this.searchlist.inspectionTaskName || undefined,
          inspectionRouteId: this.searchFormData.inspectionRouteId || this.searchlist.inspectionRouteId || undefined,
          beforeFlagList: [2, 3],
          checkFlag: false,
          employeeName: this.searchFormData.employeeName || this.searchlist.employeeName || undefined,
          dataTimeStart: this.searchFormData.dataTimeStart || this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          dataTimeEnd: this.searchFormData.dataTimeEnd || this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
          organizationNo: sessionStorage.organizationNo
        }
      };
      InspectionTask.getInspectionTaskList(params).then(res => {
        this.loading = false;
        let data = res.data;
        // console.log(data);
        if (data) {
          this.tableData = data.content;
          this.totalSize = data.totalElements;
          // this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogFormVisible = true
        this.nowChanceStau = "add"
      } else if (flag == 'delete') {
        if (this.delActive) {
          this.delmessage()
        } else {
          this.$message.warning('请先选择删除项')
        }
      }
    },
    employee(e) {
      let obj = this.person.find(item => item.person.personNo === e);
      this.$set(this.formData, "employeeName", obj.person.name);
    },
    inspection(e) {
      this.patrolLine.forEach(element => {
        if (element.inspectionRouteId === e) {
          this.$set(
            this.formData,
            "inspectionRouteName",
            element.inspectionRouteName
          );
        }
      });
    },
    // 时间转换
    dateFormat(row, colnum) {
      if (row.inspectionTaskId) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD");
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    selectable(row, index) {
      // console.log(row)
      return row.beforeFlag !== 2; // 通过某个值来进行判断，规定那一行的选择框被禁用
    },

    add() {
      this.canInput = true;
      this.formData = {};
      this.openDialog("add");
    },
    handleEdit(row) {
      //  TODO 点击行元素后 edit
      this.formData = JSON.parse(JSON.stringify(row));
      //   this.formData.employeeId = row.employeeId;
      // console.log(row)
      if (this.formData.beforeFlag === 2) {
        this.addActive = true;
        this.editActive = false;
        this.saveActive = false;
        this.delActive = false;
        this.cancelActive = false;
        this.canInput = false;
        this.$message.warning("自动任务不可修改！");
      } else {
        this.addActive = false;
        this.editActive = true;
        this.saveActive = false;
        this.delActive = false;
        this.cancelActive = true;
        this.canInput = false;
      }
      // this.$refs.formData.resetFields();/**/
      // this.openDialog('edit');
    },
    // cancel(){
    //   this.formData = {};
    //   this.closeDialog();
    // },
    handleSelectionChange(list) {
      this.inspectionTaskIdList = [];
      this.inspectionTaskIdList = list.map(item => item.inspectionTaskId);
      if (this.inspectionTaskIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      InspectionTask.delInspectionTaskInfo(this.inspectionTaskIdList).then(
        res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.getTableDataList();
            this.resetActionBar();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        }
      );
    },
    handleDelete(row) {
      // InspectionTask.delInspectionTaskInfo([row.inspectionTaskId]).then(
      //   res => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       // this.$refs[formData].resetFields();
      //       this.getTableDataList();
      //       this.resetActionBar();
      //     } else {
      //       this.$message.warning(res.msg || '删除失败');
      //     }
      //   }
      // );
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          InspectionTask.delInspectionTaskInfo([row.inspectionTaskId]).then(
            res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.getTableDataList();
                this.resetActionBar();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            }
          );
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            InspectionTask.editInspectionTaskInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // if (this.formData.inspectionTaskId) {
            //   delete this.formData.inspectionTaskId
            // }
            this.formData.organizationNo = sessionStorage.organizationNo;
            this.formData.checkFlag = false;
            InspectionTask.addInspectionTaskInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.closeDialog();
                this.$refs[formData].resetFields();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.staff-manage {
  width: 100%;
  height: 100%;

  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
  }

  ::v-deep .el-input__inner {
    background-color: transparent;
    color: #fff;
    // border-radius: 5px;
    border-color: #6ecae3;
  }

  ::v-deep .el-form-item__label {
    min-width: 120px !important;
    text-align: end;
  }

  .common-layout {
    // border: 1px solid $borderColor;
    height: calc(100% - #{$actionBarHeight + 10});
    padding: 20px;

    .search-box {
      display: flex;
      align-items: center;
      margin: 0 0 10px 0;

      .label-input {
        display: flex;
        align-items: center;

        // .input {
        //   // .el-input {
        //   //   width: 300px;
        //   //   ::v-deep .el-input__inner {
        //   //     // border-radius: 5px;
        //   //   }
        //   // }
        // }
        .label {
          width: 120px !important;
          white-space: nowrap;
        }
      }

      .search {
        display: flex;
        align-items: center;

        img {
          height: 30px;
        }
      }
    }

    .content {
      height: calc(100% - 50px);
      margin: 10px 0;
      display: flex;

      .left-box {
        width: 59%;
        height: 100%;
      }

      .table-box {
        height: calc(100% + 20px);
        position: relative;
        overflow-y: auto;

        //   border-radius: 8px;
        .el-table {
          background-color: transparent;
          color: #fff;
          // border-radius: 12px;
        }
      }

      .right-box {
        width: 39%;
        // height:100%;
        height: calc(100% - 50px);
        margin-left: 2%;
        border: 1px dashed rgba($color: #fff, $alpha: 0.6);
        border-radius: 10px;
        padding: 1% 2%;

        .form {
          overflow-x: auto;
          height: 100%;
          width: 100%;
          // border-top: 1px solid $borderColor;
          padding-top: 20px;

          .el-form {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;

            .el-form-item {
              .sort-box {
                display: inline-block;
                // width: 60px;
                transform: rotateY(180deg);

                .sort {
                  padding: 0 5px;
                  transform: rotate(-90deg);
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
